package com.shanshan.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.code.kaptcha.Producer;
import com.shanshan.system.entity.Code;
import com.shanshan.system.service.CodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * -*- coding:utf-8 -*-
 *
 * @author 太阳偷渡青山
 * @software IntelliJ IDEA
 * @date 2023/01/02 10:29
 * @Description 验证码操作处理
 */
@RestController
@Api("验证码接口")
@Slf4j
@RequestMapping("/captchaImage")
public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Resource
    private CodeService codeService;
    /**
     * 生成验证码
     */
    @PostMapping
    @ApiOperation("生成验证码")
    public com.shanshan.system.vo.Result getCode(HttpServletResponse response) throws IOException {

        Map<String,Object> ajax = new HashMap<>();

        // 保存验证码信息
        String uuid = UUID.randomUUID().toString();

        // 生成验证码
        String capText = captchaProducerMath.createText();
        String capStr = capText.substring(0, capText.lastIndexOf("@"));
        String code = capText.substring(capText.lastIndexOf("@") + 1);
        BufferedImage image = captchaProducerMath.createImage(capStr);

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return new com.shanshan.system.vo.Result(444,e.getMessage());
        }
        // 将数据保存到数据库中
        Code sysCode = new Code(uuid,code,new Date());
        codeService.save(sysCode);

        log.info("code === {}" ,code);

        ajax.put("uuid", uuid);
        ajax.put("img", com.shanshan.system.util.Base64.encode(os.toByteArray()));
        return new com.shanshan.system.vo.Result(200,"验证码获取成功",ajax);
    }

    @GetMapping
    @ApiOperation("匹配验证码是否正确")
    public com.shanshan.system.vo.Result isCode(String code , String uuid){

        /* 核心代码 计算1分钟之前的时间*/
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -1);
        Date beforeD = beforeTime.getTime();
        String before5 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(beforeD);

        LambdaQueryWrapper<Code> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(Code::getCreateTime,before5,new Date());
        queryWrapper.eq(Code::getUuid,uuid);
        Code one = codeService.getOne(queryWrapper);
        if (code == null) {
            return new com.shanshan.system.vo.Result(444,"验证码不能为空");
//            throw new RuntimeException("验证码不能为空");
        }else if (one == null){
            return new com.shanshan.system.vo.Result(444,"验证码已过期");
        }else if (code.equals(one.getCode())){
            return new com.shanshan.system.vo.Result(200,"验证码正确");
        }else {
            return new com.shanshan.system.vo.Result(444,"验证码输入错误");
//            throw new RuntimeException("验证码输入错误");
        }
    }
}
